package alo.p6;

import java.util.Stack;

/**
 * @ClassName BuildExprTree
 * @Description 表达式树
 * @Author Fanxc
 * @DATE 2021/2/7 12:53
 * @Version 1.0
 */
public class BuildExprTree {
    BinaryTreeNode buildExprTree(char[] postfixExpr,int size){
        Stack<BinaryTreeNode> stack=new Stack<>();
        for (int i = 0; i < size; i++) {
            //是运算符
            if (isOperand(postfixExpr[i])){
                BinaryTreeNode T1 = stack.pop();
                BinaryTreeNode T2 = stack.pop();
                BinaryTreeNode newNode = new BinaryTreeNode();
                newNode.setData(postfixExpr[i]);
                newNode.setLeft(T1);
                newNode.setRight(T2);
                stack.push(newNode);
            }else {//是运算数
                BinaryTreeNode newNode = new BinaryTreeNode();
                newNode.setData(postfixExpr[i]);
                newNode.setLeft(null);
                newNode.setRight(null);
                stack.push(newNode);
            }
        }
        return stack.pop();
    }

    private boolean isOperand(char ch) {
        return ch == '+' || ch == '-' || ch == '*' || ch == '/';
    }

}
